package org.example;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import org.example.chrome.ChromeUtils;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class Main2 {
    public static void main(String[] args) throws Exception {
        String txt = readClipboard();
        if (Strings.isNullOrEmpty(txt)) {
            System.out.println("请先复制投票信息");
            TimeUnit.HOURS.sleep(1);
            return;
        }
        // 清空剪切板
        Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
        sysClip.setContents(new StringSelection(""), null);

        JSONObject json = JSONObject.parseObject(txt);
        ChromeOptions options = new ChromeOptions();
        // 设置代理
        String proxy = json.getString("proxy");
        if (Strings.isNullOrEmpty(proxy)) {
            System.out.println("未检测到 proxy 信息");
            TimeUnit.HOURS.sleep(1);
            return;
        }
        String[] _proxy = proxy.split(":");
        File f = ChromeUtils.create_proxyauth_extension(_proxy[0], _proxy[1], "2mjjzn", "1s4qnr8r");
        options.addExtensions(f);
        // 设备信息
        Map<String, String> mobileEmulation = Maps.newHashMap();
//        mobileEmulation.put("deviceName", json.getString("deviceName"));
        mobileEmulation.put("userAgent", json.getString("userAgent"));
        options.setExperimentalOption("mobileEmulation", mobileEmulation);
        WebDriver DRIVER = new RemoteWebDriver(ChromeUtils.SERVICE.getUrl(), options);
        DRIVER.get(json.getString("link"));
        TimeUnit.MINUTES.sleep(30);
    }

    public static String readClipboard() {
        String ret = "";
        Clipboard sysClip = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 获取剪切板中的内容
        Transferable clipTf = sysClip.getContents(null);

        if (clipTf != null) {
            // 检查内容是否是文本类型
            if (clipTf.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                try {
                    ret = (String) clipTf
                            .getTransferData(DataFlavor.stringFlavor);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return ret;
    }
}